package main

import (
	"github.com/gin-contrib/cors"
	"github.com/gin-gonic/gin"
	"github.com/redis/go-redis/v9"
	"ruoyi-go/internal/core/auth"
	"ruoyi-go/internal/framework/db"
	"ruoyi-go/internal/framework/redisclient"
	"ruoyi-go/internal/framework/utils/conf"
	"ruoyi-go/internal/web/common"
	"ruoyi-go/internal/web/system"
	"time"
)

func main() {
	// 解析yml
	ymlMap, err := conf.ParseYAMLFileToFlatMap("etc/application.yml")
	if err != nil {
		panic(err)
	}
	// 创建服务
	router := gin.Default(func(engine *gin.Engine) {
		// 初始化gin中间件
		engine.Use(cors.New(cors.Config{ // 允许跨域
			AllowOrigins:     []string{"*"}, // 測試環境先讓所有domian通過
			AllowHeaders:     []string{"Origin", "Content-Length", "Content-Type", "Authorization"},
			AllowMethods:     []string{"GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"},
			AllowCredentials: false,         // 无需传递cookie等认证信息
			MaxAge:           2 * time.Hour, // 缓存12小时
		}))
		engine.Use(auth.JWTAuthMiddleware()) // jwt安全验证

		// 启动三方组件
		db.Init(db.Settings{ // mysql
			Url:         ymlMap["db.url"],
			MaxIdleConn: ymlMap["db.max-idle-conn"],
			MaxOpenConn: ymlMap["db.max-open-conn"],
		})
		redisclient.Init(&redis.Options{ // redis
			Addr:     ymlMap["redis.host"],
			Password: ymlMap["redis.pass"],
		})

		// 注册路由
		common.RegisterRouterForCaptcha(engine)
		system.RegisterWebLoginRouter(engine)
		system.RegisterSysDeptRouter(engine)
		system.RegisterProfileRouter(engine)
	})

	// 端口默认为8080
	port := func() string {
		if port, ok := ymlMap["app.port"]; ok && port != "" {
			return port
		} else {
			return "8080"
		}
	}()
	router.Run("0.0.0.0:" + port) // 启动服务
}
